<template>
  <div>
    <h1 class="con-right-title">问卷列表</h1>
    
    <!-- 顶部搜索 -->
    <div class="search-row search-box">
      <el-form :inline="true" :model="formInline" class="demo-form-inline">
        <el-form-item label="问卷名称">
          <el-autocomplete
            v-model="formInline.questionName"
            :fetch-suggestions="querySearchAsync"
            :maxlength="40"
            :clearable="true"
            placeholder="问卷名称"
            style="width:280px;"
          ></el-autocomplete>
        </el-form-item>

        <el-form-item>
          <el-button type="success" icon="el-icon-search" @click="onSearch">查询</el-button>
        </el-form-item>

        <el-form-item>
          <el-button type="success" plain @click="onReset">重置</el-button>
        </el-form-item>

        <el-form-item style="margin-left:30px;" v-permission="'wh:surveyList:add'">
          <el-button type="success" icon="el-icon-plus" @click="onAdd">新增问卷</el-button>
        </el-form-item>
      </el-form>
    </div>

    <!--table 刷新-->
    <div class="table-conBtn">
      <freshCom @searchList="searchList"></freshCom>
    </div>

    <!--table 列表-->
    <div class="table-box">
      <el-table ref="table" stripe v-loading="loading" :data="tableData" :fit="true" max-height="490">
        <el-table-column type="index" label="序号">
          <template slot-scope="scope">
            {{ scope.$index | filterPage(searchParams.pageNum, searchParams.pageSize) }}
          </template>
        </el-table-column>

        <el-table-column label="问卷学院" prop="collegeName" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.collegeName }}</span>
          </template>
        </el-table-column>

        <el-table-column label="问卷名称" prop="questionName" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.questionName }}</span>
          </template>
        </el-table-column>

        <el-table-column label="引用模版" prop="template" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.templateId | templateFilter }}</span>
          </template>
        </el-table-column>

        <el-table-column label="状态" prop="questionState" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.questionState | statusFilter }}</span>
          </template>
        </el-table-column>

        <el-table-column label="创建者" prop="userName" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.userName }}</span>
          </template>
        </el-table-column>

        <el-table-column label="回收答卷数" prop="answerStatistics" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.questionState !== 'NOT_STARTED' ? scope.row.answerStatistics : '---' }}</span>
          </template>
        </el-table-column>

        <el-table-column label="问卷周期" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.startTime + ' 至 ' + scope.row.endTime }}</span>
          </template>
        </el-table-column>

        <el-table-column label="问卷创建时间" prop="createTime" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.createTime }}</span>
          </template>
        </el-table-column>

        <el-table-column label="实际结束时间" prop="actualEndTime" align="center">
          <template slot-scope="scope">
            <template v-if="scope.row.questionState === 'IN_PROGRESS' || scope.row.questionState === 'HAS_ENDED'">
              <span>{{ scope.row.actualEndTime ? scope.row.actualEndTime : scope.row.endTime }}</span>
            </template>
            <template v-else>
              <span>{{ scope.row.actualEndTime ? scope.row.actualEndTime : '---' }}</span>
            </template>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <span v-permission="'wh:surveyList:coryLink'" class="button-space">
              <el-button v-if="scope.row.questionState === 'NOT_STARTED' || scope.row.questionState === 'IN_PROGRESS'" type="text" @click="handleCopy(scope.row)">
                复制链接
              </el-button>
            </span>

            <span v-permission="'wh:surveyList:edit'" class="button-space">
              <el-button v-if="scope.row.questionState === 'NOT_STARTED'" type="text" @click="handleEdit(scope.row)">
                编辑
              </el-button>
            </span>

            <span class="button-space">
              <el-button type="text" @click="handleDetails(scope.row)" v-permission="'wh:surveyList:view'">
                查看
              </el-button>
            </span>

            <span v-permission="'wh:surveyList:remove'" class="button-space">
              <el-button v-if="scope.row.questionState === 'NOT_STARTED'" type="text" @click="handleDel(scope.row)">
                删除
              </el-button>
            </span>

            <span v-permission="'wh:surveyList:end'" class="button-space">
              <el-button v-if="scope.row.questionState === 'IN_PROGRESS'" type="text" @click="handleEnd(scope.row)">
                结束
              </el-button>
            </span>

            <span v-permission="'wh:surveyList:viewAnswer'" class="button-space">
              <el-button v-if="scope.row.questionState === 'HAS_ENDED'" type="text" @click="handleData(scope.row)">
                查看答卷数据
              </el-button>
            </span>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <!--分页-全局组件-->
    <pageCom :searchParams="searchParams" :total="total" @searchList="searchList"></pageCom>

    <!-- 新增、编辑、查看问卷弹框 -->
    <survey-dialog :dialogForm="dialogForm" @onSubmit="onSubmit"></survey-dialog>

    <!-- 关闭问卷 确认弹框 -->
    <el-dialog title="提示" width="30%" :visible.sync="confirmDialog.visible">
      <span>当前问卷还未结束，您确定要手动关闭此问卷吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button type="success" plain @click="handleCancel">取 消</el-button>
        <el-button type="success" @click="handleConfirm">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import surveyDialog from '@/components/survey/surveyList/surveyDialog.vue'

import {
  questionnaires, 
  delQuestionnaires,
  endQuestionnaires
} from '@/api/survey'

const templates = {
  1: { key: 'shengxue', templateName: '升学意向度问卷'},
  2: { key: 'zhuanxianger', templateName: '专项2满意度调查问卷'},
  3: { key: 'zhuanxiangyi', templateName: '专项1满意度调查问卷'},
  4: { key: 'rumen', templateName: '入门课满意度调查问卷'}
}

const status = {
  NOT_STARTED: { text: '问卷待开始'},
  IN_PROGRESS: { text: '问卷进行中'},
  HAS_ENDED: { text: '问卷已结束'}
}

export default {
  msg: '问卷列表',
  components: {
    surveyDialog
  },
  data() {
    return {
      total: 0,
      loading: true,
      tableData: [],
      searchParams: {
        pageNum: 1,
        pageSize: 10
      },
      timeout: null,
      formInline: {
        questionName: ''
      },
      confirmDialog: {
        visible:false ,
        currObj: null
      },
      dialogForm: {
        type: '',
        questionId: '',
        visible: false
      }
    }
  },
  mounted() {
    this.searchList()
  },

  filters: {
    templateFilter (type) {
      return templates[type].templateName
    },

    statusFilter (type) {
      return status[type].text
    }
  },

  methods: {
    // 查询问卷列表
    searchList() {
      this.loading = true
      
      let params = { ...this.searchParams, ...this.formInline }

      questionnaires(params, (res) => {
        this.total = res.total
        this.tableData = res.rows
        this.loading = false
      },(err) => {
        this.$message({
          message: err.message,
          type: 'warning'
        })
      })
    },

    // 提交问卷
    onSubmit() {
      this.searchList()
      this.dialogForm.visible = false
    },

    // 查询
    onSearch() {
      this.searchParams.pageNum = 1
      this.searchList()
    },

    // 重置
    onReset() {
      this.formInline.questionName = ''
    },

    // 新增问卷
    onAdd() {
      this.dialogForm.type = 'add'
      this.dialogForm.visible = true
    },

    // 查看答卷数据
    handleData(item) {
      this.$router.push({
        name: 'wh:survey:surveyList:answer',
        query: {
          questionId: item.id,
          questionName: item.questionName,
          collegeId: item.collegeId
        }
      })
    },

    /** 复制链接 */
    handleCopy(item) {
      const _this = this
      const template = templates[item.templateId].key
      const params = `/survey/?type=${template}&id=${item.id}`
      const URL = process.env.VUE_APP_WAP_URL + params
      this.$copyText(URL).then(function (e) {
        _this.$message.success('复制成功')
      }, function (e) {
        _this.$message.error('复制失败')
      })
    },

    /* 编辑 */
    handleEdit(item) {
      this.dialogForm.type = 'edit'
      this.dialogForm.questionId = item.id
      this.dialogForm.visible = true
    },

    /* 查看详情 */
    handleDetails(item) {
      this.dialogForm.type = 'preview'
      this.dialogForm.questionId = item.id
      this.dialogForm.visible = true
    },

    /* 删除 */
    handleDel(row) {
      delQuestionnaires(row.id, (res) => {
        this.searchList()
      }, (err) => {
        this.$message({
          message: err.message,
          type: 'warning'
        })
      })
    },

    // 处理确定事件
    handleConfirm() {
      const row = this.confirmDialog.currObj
      this.confirmDialog.visible = false
      endQuestionnaires(row.id, (res) => {
        this.searchList()
      }, (err) => {
        this.$message({
          message: err.message,
          type: 'warning'
        })
      })
    },

    // 处理取消事件
    handleCancel() {
      this.confirmDialog.visible = false
    },

    // 结束问卷确认
    handleEnd(row) {
      this.confirmDialog.currObj = row
      this.confirmDialog.visible = true
    },

    /* 换页 */
    changePage(page) {
      this.searchParams.pageNum = page
      this.searchList()
    },
    
    /* 搜索 */
    toSearch() {
      this.searchParams.pageNum = 1
      this.searchList()
    },
    
    /* 刷新列表 */
    refresh() {
      this.searchList()
    },

    // 过滤问卷模板
    async querySearchAsync(queryString, cb) {
      let results = queryString ? await this.createStateFilter(queryString) : []
      clearTimeout(this.timeout)
      this.timeout = setTimeout(() => {
        cb(results)
      }, 2000 * Math.random())
    },

    // 创建问卷过滤器
    createStateFilter(queryString) {
      return new Promise((resolve, reject) => {
        let data = []
        const params = { ...this.searchParams, questionName: queryString }

        questionnaires(params, (res) => {
          res.rows && res.rows.forEach(element => {
            data.push({ value: element.questionName })
          })

          resolve(data)
        },(err) => {
          this.$message({
            message: err.message,
            type: 'warning'
          })
        })
      })
    }
  }
}
</script>

<style scoped>
.table-box .button-space {
  margin-left: 5px;
}
</style>
